import {ChangeDetectorRef, Component, QueryList, ViewChild, ViewChildren, NgZone, ElementRef} from "@angular/core";
import {AlertController, Content, IonicPage, NavController, ToastController} from "ionic-angular";
import $ from "jquery";

import {InformationListProvider} from '../../../providers/information/information-list/information-list.provider';
import {Info} from '../../../model/pages/information/information-list/information-list.model';
import {BASEURL} from "../../../config/url.config";
import {AdpLazyloadComponent} from "../../../components/common/adp-lazyload/adp-lazyload.component";
import {ToastService} from '../../../services/common/toast.service';
import {LoadingService} from "../../../services/common/loading.service";
import {ThemeBrowserService} from '../../../services/native/theme-browser/theme-browser.service';
import {InformationDetailProvider} from '../../../providers/information/information-detail/information-detail.provider';

import {FileService} from "../../../services/native/file/file.service";
import {LocalStorageService} from "../../../services/native/local-storage/local-storage.service";
import {File} from "@ionic-native/file";
import {FileTransfer} from "@ionic-native/file-transfer";
import {CacheImgService} from '../../../services/native/cache-img/cache-img.service';

@IonicPage()
@Component({
    selector: 'page-information-list',
    templateUrl: 'information-list.html',
    providers:[
        InformationListProvider,
        ToastService,
        ThemeBrowserService,
        InformationDetailProvider,
        FileService,
        LocalStorageService,
        File,
        FileTransfer,
        CacheImgService
    ]
})
export class InformationListPage {
    @ViewChild(Content) content: Content;
    @ViewChildren(AdpLazyloadComponent) lazyImgs: QueryList<AdpLazyloadComponent>;
    @ViewChild('list') list:ElementRef;
    // 查询关键字
    private keyword:string='';
    // 咨询列表数据
    private infoListData:Info[]=[];
    // 视口高度
    get clientItemHeight():string{
        const windowW = window['innerWidth'];
        return (windowW * 38.34 / 100) + 'px';
    }
    // 内容是否滚动
    private isScrolling = false;
    // 请求状态
    private requestStatus:boolean;
    // 预览列表长度
    private previewLength:number=0;
    // 图片是否下载标记对象
    private signImg:any={};

    private azureInfo;
    // 回车键请求状态
    private enterStatus:boolean=true;

    constructor (private zone:NgZone,
                 private navCtrl: NavController,
                 private informationListProvider:InformationListProvider,
                 private toastCtrl:ToastController,
                 private ref: ChangeDetectorRef,
                 private toastService:ToastService,
                 private load: LoadingService,
                 private themeBrowserService:ThemeBrowserService,
                 private informationDetailProvider:InformationDetailProvider,
                 private fileService:FileService,
                 private cacheImgService:CacheImgService
                 ) {}

    ionViewDidLoad(){

    }

    ionViewDidEnter(){
        this.getAzureInfo ();
    }

    // 返回
    backClickHandle(){
        this.navCtrl.pop();
    }

    getAzureInfo () {
        this.fileService.getAzureInfo().subscribe((data) => {
            this.azureInfo = data.azureInfo;
            this.getInformationList(this.keyword,1,20,1,null);
        }, err => {
            this.getInformationList(this.keyword,1,20,1,null);
            console.log(err);
        });
    }

    // 获取咨询列表
    getInformationList(keyword,pageNum,pageSize,loading,fn){
        this.enterStatus=false;
        loading?this.load.showLoading():null;
        this.informationListProvider.getInformation(keyword,pageNum,pageSize).subscribe((res)=>{
            fn?fn():null;
            if(res.total){
                this.informationListProvider.getInformation(keyword,1,res.total).subscribe((res)=>{
                    this.getInfoPrev(res.list,loading);
                },err=>{
                    fn?fn():null;
                    this.requestStatus=true;
                    loading?this.load.dismissLoading():null;
                })
            }else{
                this.getInfoPrev([],loading);
            }
        },err=>{
            if(err.status==500){this.toastService.showToast('请求失败')}
            this.enterStatus=true;
            fn?fn():null;
            this.requestStatus=true;
            loading?this.load.dismissLoading():null;
        })
    }

    // 获取资讯预览
    getInfoPrev(list:Info[],loading){
        this.informationListProvider.getInformationPrev().subscribe((res)=>{
            this.enterStatus=true;
            loading?this.load.dismissLoading():null;
            this.requestStatus=true;
            if(res.length>0){
                this.previewLength=res.length;
                this.infoListData=res.concat(list);
            }else{
                this.infoListData=list;
            }
            this.getFullUrl();
        },error=>{
            this.enterStatus=true;
            this.requestStatus=true;
            loading?this.load.dismissLoading():null;
        })
    }

    // 获取img完整路径
    getFullUrl(){
        for(let i in this.infoListData){
            if(this.infoListData[i].imgUrl){
                let img=this.infoListData[i].imgUrl;
                //this.infoListData[i].imgUrl=BASEURL + '/azure/v1/download?resourceId='+this.infoListData[i].imgUrl;
               // this.infoListData[i].imgUrl=this.fileService.getCompletePath(this.infoListData[i].imgUrl, this.azureInfo);
                this.cacheImgService.getImgPath(this.infoListData[i].imgUrl, this.azureInfo).then((res)=>{
                    console.log(res);
                    this.infoListData[i].imgUrl=res;
                    img=res;
                }).catch(()=>{
                    console.log('img err');
                    this.infoListData[i].imgUrl=this.fileService.getCompletePath(this.infoListData[i].imgUrl, this.azureInfo);
                })
            }
        }
    }

    // 头部下拉刷新
    doRefresh(refresher){
        this.getInformationList(this.keyword,1,20,0,()=>{refresher.complete()});
    }

    // 搜索关键字
    searchKeyword(e,flag){
        if(flag){
            if(('Enter' === e.key || 13 === e.keyCode)&&this.enterStatus){
                this.getInformationList(this.keyword,1,20,1,null);
            }
        }else{
            this.getInformationList(this.keyword,1,20,1,null);
        }
    }

    scroll($event){
        let list=document.getElementById('info-list');
    }

    // 内容滚动结束
    scrollEnd($event){
        this.zone.run(()=>{
            this.ref.markForCheck();
            this.ref.detectChanges();
        });
        /*let ionThis=this;
        setTimeout(()=>{
            $('#info-list img').each(function(img,item){
                if(item['src'].indexOf('&')){
                    let srcValue=item['src'].split('&')[0];
                    if(!item['complete']&&item['src']&&ionThis.signImg[srcValue]){
                        ionThis.signImg[srcValue]='';
                    }
                    if(!item['complete']){
                        console.log('nonono')
                    }
                    item['src']=srcValue;
                }
                //item['src']=item['src']+'&'+String(Math.random()*10).substr(0,4);
                //ionThis.signImg[item['src']]='img'
            });
        },100)*/
    }

    loadImg($event,url){
        //console.log($event)
        /*if(!this.signImg[url]){
            this.signImg[url]='img';
        }*/
    }

    // 跳转至资讯详情
    goToInfoDetail (id,index,url,title,imgUrl,status) {
        if(url){
            this.informationListProvider.saveExternallinks(id,localStorage.getItem('roles')).subscribe((res)=>{
                    console.log('success');
                    this.goToBrowerPlatform(title,id,url,status)
            },error=>{
                this.goToBrowerPlatform(title,id,url,status)
            });
            return false;
        }
        let isNormal=false;
        if(this.previewLength>0&&index<=(this.previewLength-1)) {
            isNormal = true;
        }
        this.navCtrl.push('InformationDetailPage',{
            id:id,
            status:isNormal,
            url:url?url:'',
            imgUrl:imgUrl
        });
    }

    // 外链到浏览器平台
    goToBrowerPlatform(name,id,url,status){
        let statusValue:boolean;
        status?statusValue=true:statusValue=false;
        this.themeBrowserService.openBrowser(url,{name:name,id:id,status:statusValue,callback1:(id)=>this.collectInfo(id),callback2:(id)=>this.cancelInfo(id)})
    }

    // 收藏资讯
    collectInfo(id){
        this.informationDetailProvider.collectInfo(id).subscribe(()=>{
            this.themeBrowserService.setStatus(true);
            this.getInformationList(this.keyword,1,20,0,null);
        },error=>{
        })
    }

    // 取消收藏
    cancelInfo(id){
        this.informationDetailProvider.cancelCollect(id).subscribe(()=>{
            this.themeBrowserService.setStatus(false);
            this.getInformationList(this.keyword,1,20,0,null);
        },error=>{
        })
    }

    // 到收藏列表
    goToCollectionList () {
        this.navCtrl.push('CollectionListPage',{
            type:2
        });
    }
}
